import os

import yaml

# 全局缓存配置
_config = None


# 获取项目路径
def get_project_path():
    """使用纯字符串操作确保路径兼容性"""
    current_dir = os.path.dirname(os.path.abspath(__file__))
    project_path = os.path.normpath(os.path.join(current_dir, '..', '..'))
    return project_path




def load_config(force_reload=False):
    global _config
    if force_reload or _config is None:
        env = os.getenv('APP_ENV', 'dev').lower()

        # 使用 os.path 拼接路径
        config_path = os.path.join(
            get_project_path(),
            'conf',
            f'config-{env}.yml'
        )

        # 检查文件是否存在
        if not os.path.exists(config_path):
            print(f"错误：配置文件不存在，请检查路径。路径为: {config_path}")
            raise RuntimeError(f"配置文件不存在: {config_path}")
        try:
            with open(config_path, 'r') as f:
                _config = yaml.safe_load(f)
                # 启动信息打印
                print(f"\n⚙️  当前运行环境: {env}")
                # print(f"🔗 mysql数据库地址: {_config['database']['host']}:{_config['database']['port']}\n")
                # print(f"🔗 redis数据库地址: {_config['redis']['host']}:{_config['redis']['port']}\n")
                # print(f"🔗 clickhouse数据库地址: {_config['clickhouse']['host']}:{_config['clickhouse']['port']}\n")

        except KeyError as e:
            raise ValueError(f"配置缺少必要字段: {e}")

    return _config
